package com.atlin.project.controller.cds;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.cds.FileMetadata;
import com.atlin.project.model.dto.fileMetadata.FileMetadataAddRequest;
import com.atlin.project.model.dto.fileMetadata.FileMetadataQueryRequest;
import com.atlin.project.model.dto.fileMetadata.FileMetadataUpdateRequest;
import com.atlin.project.model.vo.cds.FileMetadataVO;
import com.atlin.project.service.SysUserService;
import com.atlin.project.service.FileMetadataService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 文件元数据
 *
 * @author atlin
 */
@RestController
@RequestMapping("/fileMetadata")
public class FileMetadataController {

    @Resource
    private FileMetadataService fileMetadataService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param fileMetadataAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addFileMetadata(@RequestBody FileMetadataAddRequest fileMetadataAddRequest, HttpServletRequest request) {
        if (fileMetadataAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        FileMetadata fileMetadata = new FileMetadata();
        BeanUtils.copyProperties(fileMetadataAddRequest, fileMetadata);

        fileMetadataService.valid(fileMetadata, true);
        SysUser loginUser = sysUserService.getLoginUser(request);

        // todo

        boolean result = fileMetadataService.save(fileMetadata);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newFileMetadataId = fileMetadata.getId();
        return ResultUtils.success(newFileMetadataId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteFileMetadata(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        FileMetadata oldfileMetadata = fileMetadataService.getById(id);
        ThrowUtils.throwIf(oldfileMetadata == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldfileMetadata.getUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = fileMetadataService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param fileMetadataUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateFileMetadata(@RequestBody FileMetadataUpdateRequest fileMetadataUpdateRequest) {
        if (fileMetadataUpdateRequest == null || fileMetadataUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        FileMetadata fileMetadata = new FileMetadata();
        BeanUtils.copyProperties(fileMetadataUpdateRequest, fileMetadata);

        // 参数校验
        fileMetadataService.valid(fileMetadata, false);
        long id = fileMetadataUpdateRequest.getId();
        // 判断是否存在
        FileMetadata oldfileMetadata = fileMetadataService.getById(id);
        ThrowUtils.throwIf(oldfileMetadata == null, ErrorCode.NULL_ERROR);
        // todo other operation

        boolean result = fileMetadataService.updateById(fileMetadata);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<FileMetadata> getFileMetadataById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        FileMetadata fileMetadata = fileMetadataService.getById(id);
        if (fileMetadata == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!fileMetadata.getUserId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(fileMetadata);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<FileMetadataVO> getFileMetadataVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        FileMetadata fileMetadata = fileMetadataService.getById(id);
        if (fileMetadata == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        FileMetadataVO fileMetadataVO = FileMetadataVO.objToVo(fileMetadata);
        return ResultUtils.success(fileMetadataVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param fileMetadataQueryRequest 查询参数
     * @param request              查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<FileMetadataVO>> listFileMetadataVOByPage(@RequestBody FileMetadataQueryRequest fileMetadataQueryRequest,
                                                               HttpServletRequest request) {
        long current = fileMetadataQueryRequest.getCurrent();
        long size = fileMetadataQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<FileMetadata> fileMetadataPage = fileMetadataService.page(new Page<>(current, size),
                fileMetadataService.getQueryWrapper(fileMetadataQueryRequest));

        Page<FileMetadataVO> fileMetadataVOPage = fileMetadataService.getFileMetadataVOPage(fileMetadataPage, request);

        return ResultUtils.success(fileMetadataVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param fileMetadataQueryRequest 查询参数
     * @param request              查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<FileMetadata>> listFileMetadataByPage(@RequestBody FileMetadataQueryRequest fileMetadataQueryRequest,
                                                           HttpServletRequest request) {
        long current = fileMetadataQueryRequest.getCurrent();
        long size = fileMetadataQueryRequest.getPageSize();
        Page<FileMetadata> fileMetadataPage = fileMetadataService.page(new Page<>(current, size),
                fileMetadataService.getQueryWrapper(fileMetadataQueryRequest));
        return ResultUtils.success(fileMetadataPage);
    }

    // endregion

}
